import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:u_push_plugin/data.dart';

class UPushPlugin {
  static String _deviceToken;
  static const MethodChannel _channel = const MethodChannel('u_push_plugin');
  static const EventChannel _eChannel = const EventChannel('u_push_plugin_e');
  static ValueChanged<LoginData> _loginListener;
  static ValueChanged<Map> _messageListener;


  static Future showNotificaitonOnForeground({bool show = false}) async {
    await _channel.invokeMethod("showNotificaitonOnForeground", {"show": show});
  }

  static Future setNoDisturbMode({
    int startHour = 0,
    int endHour = 0,
    int startMin = 0,
    int endMin = 0,
  }) async {
    await _channel.invokeMethod("setNoDisturbMode", {
      "startHour": startHour,
      "endHour": endHour,
      "startMin": startMin,
      "endMin": endMin,
    });
  }

  static Future getDeviceToken() async {
    var value = await _channel.invokeMethod("getDeviceToken");
    print(value);
    return value;
  }

  static Future<Map<dynamic, dynamic>> getCacheMessage() async {
    Map<dynamic, dynamic> value = await _channel.invokeMethod("getCacheMessage");
    print("初始数据$value");
    Map<dynamic, dynamic> messageData = value["data"];
    return messageData;
  }

  static initMessageListener() {
    _eChannel.receiveBroadcastStream().listen((event) {
      Map messageData = event["data"];
      print("SLUPush数据${event["data"]}");
      switch (event["type"]) {
        case 101: //登录
          LoginData data = LoginData(messageData);
          _deviceToken = data.code == 1 ? data.message : "";
          _loginListener?.call(data);
          break;
        case 102:
          _messageListener.call(messageData);
          break;
      }
    });
  }

  static initRegisterListener(ValueChanged<LoginData> loginListener){
    _loginListener = loginListener;
  }

  static initMessageResultListener(ValueChanged<Map> messageListener){
    _messageListener = messageListener;
  }
}
